<template>
  <div class="mail-write-fa">
    <div class="mail-write">
      <el-form :model="mailForm" :rules="rules" ref="mailForm">
        <el-form-item label="收件人" prop="toInput">
          <el-input v-model="mailForm.toInput" placeholder="请输入收件人（多个邮箱用分号分隔）" @focus="show = 'to'" ></el-input>
        </el-form-item>
        <el-button @click="showCcBox ?  removeCc():showCc()">
          {{ showCcBox ? '删除抄送' : '添加抄送' }}
        </el-button>
        <el-button @click="showBccBox ?  removeBcc():showBcc()">
          {{ showBccBox ? '删除密送' : '添加密送' }}
        </el-button>
        <div v-show="showCcBox" >
          <el-form-item label="抄送" prop="ccInput">
            <el-input v-model="mailForm.ccInput"  placeholder="请输入抄送人" @focus="show = 'cc'"></el-input>
          </el-form-item>
        </div>
        <div v-show="showBccBox" >
          <el-form-item label="密送" prop="bccInput">
            <el-input v-model="mailForm.bccInput"  placeholder="请输入密送人" @focus="show = 'bcc'"></el-input>
          </el-form-item>
        </div>
        <el-form-item label="主题" prop="subject">
          <el-input v-model="mailForm.subject" placeholder="请输入主题" ></el-input>
        </el-form-item>
        <el-upload
            class="upload-file"
            action="http://localhost:8989/attachment/upload"
            :on-change="handleFileChange"
            :on-success="handleUploadSuccess"
            :on-preview="handlePreview"
            :on-error="handleUploadError"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :file-list="fileList"
            multiple
            :limit="3"
            :auto-upload="false"
            :show-file-list="true"
            drag
        >
          <i class="el-icon-link"></i>
          <div slot="tip" class="el-upload__tip">附件上传</div>

        </el-upload>
        <div v-if="attachments.length > 0" class="mail-attachment">
          <el-icon-paperclip><h3>已上传附件</h3></el-icon-paperclip>
          <el-row v-for="attachment in attachments" :key="attachment.attachmentId">
            <el-col :span="24">
              <el-link :href="attachment.storagePath" target="_blank" >
                <el-button type="text" @click="downloadFile(attachment)">
                  {{ attachment.fileName }}</el-button></el-link>
              <el-button type="text" @click="deleteAttachment(attachment)">删除</el-button>
            </el-col>
          </el-row>
        </div>
        <quill-editor
            ref="QuillEditor"
            :options="editorOption"
            v-model="mailForm.content" >
        </quill-editor>
        <el-button type="primary" @click="submitDraftForm()">保存草稿</el-button>
        <el-button type="primary" @click="submitForm()">发送</el-button>
      </el-form>
    </div>
    <div class="mail-contact">
      <p>通讯录</p>
      <el-input placeholder="搜索联系人" v-model="searchQuery" @input="updateFilteredContacts"></el-input>
      <el-collapse v-model="activeNames" >
        <el-collapse-item v-for="group in groups"
                          :key="group.groupId"
                          :name="group.groupId"
                          :title="group.groupName"
                          @header-click="handleHeaderClick(group.groupId)">
          <el-table :data="group.contacts"
                    style="width: 100%"
                    class="hide-header-table"
                    @row-click="handleRowClick"
          >
            <!--            <el-table-column prop="contactName"></el-table-column>-->
            <!--            <el-table-column prop="phone" label="电话"></el-table-column>-->
            <!-- 添加其他列以满足你的需求 -->
            <el-table-column>
              <template slot-scope="scope">
            <span style="margin-left: 10px">
           <span >
          {{ scope.row.contactName}}
           </span>
           </span>
              </template></el-table-column>
            <el-table-column>
              <template slot-scope="scope">
            <span style="margin-left: 10px">
             <span >{{ scope.row.contactName}}</span><span v-if="scope.row.remark!==null" >({{scope.row.remark}})</span>
           </span>
              </template></el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { quillEditor } from 'vue-quill-editor';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import async from "async";
import {mapGetters, mapState} from "vuex";
import ContactList from "@/views/Contact/ContactList.vue";
import validator from "validator";

export default {
  name: 'DraftDetail',
  inject: ['reload'],
  components: {
    quillEditor,
  },
  data() {
    const validateEmail=(rule, value, callback)=> {
      const emails = value.split(';');
      const trimmedEmails = emails.map(email => email.trim());
      const uniqueEmails = [...new Set(trimmedEmails)]; // 去除重复项
      // 检查是否有重复的邮箱地址
      if (trimmedEmails.length !== uniqueEmails.length) {
        callback(new Error('邮箱地址中存在重复'));
        return;
      }
      for (const email of emails) {
        if (email.trim() === '') {
          callback();
          return;
        }
        if (!validator.isEmail(email.trim())) {
          callback(new Error('邮箱地址格式不正确'));
        }
      }
      callback();
    };
    return {
      mailForm:{
        toInput:'',
        ccInput:'',
        bccInput:'',
        subject:'',
        content: '',
      },
      email:null,
      attachments:[],
      groups: [], // 存储分组信息的数组
      activeNames: [],
      showCcBox: false,
      showBccBox:false,
      show:'',
      searchQuery:'',
      editorOption:{
        placeholder: '请在这里输入',
        theme: 'snow',
      },
      fileList: [],
      rules:{
        toInput: [
          { required: true, message: '请输入收件人', trigger: 'blur' },
          { validator: validateEmail, trigger: ['blur', 'change'] },
          // 可以添加其他规则，例如非空验证等

        ],
        ccInput: [
          { required: false, message: '请输入抄送', trigger: 'blur' },
          { validator: validateEmail, trigger: ['blur'] },
          // 可以添加其他规则，例如非空验证等

        ],
        bccInput: [
          { required: false, message: '请输入抄送', trigger: 'blur' },
          { validator: validateEmail, trigger: ['blur'] },
          // 可以添加其他规则，例如非空验证等
        ],
        subject: [
          { required: false, message: '请输入主题', trigger: 'blur' },
        ],
      }

      // selectedContacts: [], // 存储当前选中的分组下的联系人列表
      // groupId:1,
      // contacts:[],

    };
  },
  watch: {
    // 监听 searchQuery 的变化，当变化时更新 filteredGroups
    searchQuery(newQuery) {
      this.updateFilteredContacts();
    },
  },
  computed: {
    ...mapState(['emailId','user']) ,// 使用mapState辅助函数从Vuex获取currentId状态
    filteredGroups() {
      return this.groups.map(group => ({
        ...group,
        // 过滤每个组的联系人
        filteredContacts: this.filterContactsByQuery(group.contacts)
      }));

    },
  },
  created() {
    this.fetchMailDetail(this.emailId);
    this.fetchAttachment(this.emailId);
    this.fetchData();
  },
  methods: {
    submitDraftForm(){
      this.$refs.mailForm.validate((valid) => {
        if (valid) {
          // 表单验证通过，执行发送邮件的逻辑
          this.saveDraft();
          if (this.$route.name !== 'MailboxList' || this.$route.params.folderId !== 1){
            this.$router.push({ path:'/mailboxList/1'});
          }
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    submitForm(){
      this.$refs.mailForm.validate((valid) => {
        if (valid) {
          // 表单验证通过，执行发送邮件的逻辑
          this.sendEmail();
          this.emailId=null;
          if (this.$route.name !== 'MailboxList' || this.$route.params.folderId !== 3){
            this.$router.push({ path:'/mailboxList/3'});
          }
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
   async fetchMailDetail(id) {
      // 假设 fetchMailDetail 是一个返回 Promise 的函数，用于从后端获取邮件详情
      console.log(id)
    await  axios.get('http://localhost:8989/email/content/'+id)
          .then(email => {
            this.email = email.data;
            this.mailForm.toInput=this.email.toMail;
            this.mailForm.ccInput=this.email.cc;
            this.mailForm.bccInput=this.email.bcc;
            this.mailForm.subject=this.email.subject;
            this.mailForm.content=this.email.content;
            console.log("emaildraft"+ this.email);
            console.log("emaildraft"+ this.email.content);
            console.log("emaildraft"+ this.email.subject);
          }).catch(error => {
        console.error('Error fetching mail detail:', error);
      });
    },
   async fetchAttachment(id) {
      // 假设 fetchMailDetail 是一个返回 Promise 的函数，用于从后端获取邮件详情
      console.log(id)
    await  axios.get('http://localhost:8989/attachment/list/'+id)
          .then(res=> {
            this.attachments=res.data;
            console.log(res.data)
            console.log("attachment"+this.attachments.length)
            for (let i = 0; i < this.attachments.length; i++) {
              this.attachments[i].fileName=this.attachments[i].fileName.substring(this.attachments[i].fileName.indexOf(".")+1);
            }


          }).catch(error => {
        console.error('Error fetching mail detail:', error);
      });
    },
    async fetchData() {
      try {
        // 获取分组列表
        const groupResponse = await axios.get('http://localhost:8989/contact/group?userId='+this.user.userId);
        console.log(groupResponse.data);
        this.groups = groupResponse.data.map(group => ({
          ...group,
          contacts: [], // 初始化每个分组的联系人列表
        }));


        // 遍历分组列表，获取每个分组的联系人
        for (const group of this.groups) {
          if(group.groupId===0){
            const contactResponse = await axios.get('http://localhost:8989/contact/all_list?userId='+this.user.userId);
            group.contacts=contactResponse.data;
          }else {
            const contactResponse = await axios.get('http://localhost:8989/contact/group_list?groupId=' + group.groupId);
            group.contacts = contactResponse.data;
            console.log("分组内容" + group.contacts);
          }
        }

        console.log(this.groups);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    },
    async saveDraft(){
     console.log("this.subject"+this.mailForm.subject);
     console.log("this.content"+this.mailForm.content);
      await axios.post('http://localhost:8989/email/update_draft', {
        emailId: this.emailId,
        toMail: this.mailForm.toInput,
        cc: this.mailForm.ccInput,
        bcc: this.mailForm.bccInput,
        subject: this.mailForm.subject,
        content: this.mailForm.content ,
        userId: this.user.userId
      })
          .then(response => {
            // 假设后端返回的是包含emailId的对象
            console.log("草稿emailId"+response.data);
            // 保存emailId以便上传附件时使用
            console.log("附件emailId"+this.emailId);

            // 如果需要，可以在这里触发附件上传
            this.uploadAttachments();

          })
          .catch(error => {
            console.error('草稿保存失败', error);
            this.$message.error('草稿保存失败！');
          });

    },
    async sendEmail(){
      await this.saveDraft();
      console.log("emailIdemail"+this.emailId);
      await  axios.post('http://localhost:8989/email/send?emailId='+this.emailId)
          .then(response => {
            // 假设后端返回的是包含emailId的对象
            console.log("发送成功"+response.data);
            this.$message.success('发送成功！');
            if(this.$route.name !== 'MailboxList'&& this.$route.params.folderId !== 3){
              this.$router.push({ path:'/home/mailboxList/3'});
              this.$router.go(0);
            }

          }).catch(error => {
            console.error('发送失败', error);
            this.$message.error('发送失败！');
          });
      this.emailId=null;


    },
    async uploadAttachments() {
      for (const file of this.fileList) {
        if (this.emailId === null) {
          this.$message.error('请先保存草稿！');
          return;
        }
        console.log("附件" + this.emailId);
        const formData = new FormData();
        formData.append('emailId', this.emailId);
        console.log("附件" + file.raw);
        formData.append('file', file.raw);
        console.log("附件1" + formData.get('file'));
        axios.post('http://localhost:8989/attachment/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(response => {
          // 处理附件上传成功后的逻辑
          // this.$message.success('附件上传成功！');
        }).catch(error => {
          // 处理附件上传失败后的逻辑
          // this.$message.error('附件上传失败！');
        });
      }


    },
    beforeRemove(file, fileList){
      return this.$confirm(`确定移除 ${ file.name }？`);

    },
   async handleRemove(file, fileList) {
      console.log("删除"+file.uid);
      const index = this.fileList.indexOf(file);
      if (index !== -1) {
        this.fileList.splice(index, 1);
      }
    },
    handleHeaderClick(groupId) {
      const index = this.activeNames.indexOf(groupId);
      if (index === -1) {
        this.activeNames.push(groupId);
      } else {
        this.activeNames.splice(index, 1);
      }
    },
   handlePreview(file){
     console.log(file);

   },
    async downloadFile(attachment) {
      alert("开始下载")
      var url = 'http://localhost:8989/attachment/download/'+attachment.attachmentId;
      window.open(url)
    },
    async deleteAttachment(attachment){
      this.$confirm('此操作将把此附件删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.post('http://localhost:8989/attachment/delete/'+attachment.attachmentId)
            .then(response => {
          // 处理附件上传成功后的逻辑
              this.$message({
                type: 'success',
                message: '已删除'
              });
          this.reload();

        }).catch(error => {
          // 处理附件上传失败后的逻辑
          this.$message.error('附件删除失败！');
        });


      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });

    },

   showCc() {
      // 添加抄送地址到草稿中的逻辑
      console.log("添加抄送")
      this.showCcBox = true;
      // 隐藏抄送框
    },
    removeCc() {
      // 隐藏抄送框并重置输入框
      this.showCcBox = false;
    },
    showBcc() {
      // 添加抄送地址到草稿中的逻辑
      console.log("添加密送")
      this.showBccBox = true;
      // 隐藏抄送框
    },
    removeBcc() {
      // 隐藏抄送框并重置输入框
      this.showBccBox = false;
    },
    handleFileChange(file, fileList) {
      // 更新fileList
      this.fileList = fileList;
    },
    handleUploadSuccess(response, file, fileList) {
      // 处理上传成功后的逻辑（如果需要）
      console.log("上传成功");
    },
    handleUploadError(error, file, fileList) {
      // 处理上传失败后的逻辑
      this.$message.error('上传失败');
    },
    handleRowClick(row) {
      switch (this.show){
        case 'to':
          this.mailForm.toInput += row.email; // 设置输入框的值为点击行的值
          if(this.mailForm.toInput!==null){
            this.mailForm.toInput+=";";
          }
          this.showToContacts = false; // 隐藏表格
          break;
        case 'cc':
          this.mailForm.ccInput += row.email; // 设置输入框的值为点击行的值
          if(this.mailForm.ccInput!==null){
            this.mailForm.ccInput+=";";
          }
          this.showCcContacts = false; // 隐藏表格
          break;
        case 'bcc':
          this.mailForm.bccInput += row.email; // 设置输入框的值为点击行的值
          if(this.mailForm.bccInput!==null){
            this.mailForm.bccInput+=";";
          }
          break;

      }
      this.show=null;

    },


  },
  mounted() {
  },
};
</script>
<style>
.hide-header-table .el-table__header {
  display: none;
}
.mail-write-fa{
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.mail-write{
  width: 70%;
  float: left;
  margin: 0 10px;
}
.mail-contact{
  width: 30%;
  float: right;
  margin: 0 10px;
}
.upload-file{
}
.el-upload .el-upload-dragger {
  width: 150px;
  height: 50px;
}
.ql-container {
  height: 400px;
}
</style>